package com.ews.onlineexchange.service.activitii;

import java.util.List;

import javax.enterprise.inject.Model;
import javax.faces.application.FacesMessage;
import javax.faces.context.FacesContext;
import javax.inject.Inject;

import org.activiti.engine.RepositoryService;
import org.activiti.engine.RuntimeService;
import org.activiti.engine.repository.Deployment;
import org.activiti.engine.repository.ProcessDefinition;
import org.activiti.engine.repository.ProcessDefinitionQuery;
import org.activiti.engine.runtime.ProcessInstance;
import org.apache.log4j.Logger;
import org.primefaces.model.UploadedFile;

@Model
public class ProcessDeployer {
		
	private static Logger logger = Logger.getLogger( ProcessDeployer.class );

	@Inject
	RepositoryService 	repositoryService;
	
	@Inject
	RuntimeService 		runtimeService;
	
	String				processKey;
	UploadedFile		uploadFile;
	
	List<ProcessDefinition> resultList;
	
	public String deploy() {
		if ( getUploadFile() == null ) {
			FacesContext.getCurrentInstance().addMessage( "processUploadFile",
					new FacesMessage( FacesMessage.SEVERITY_ERROR, "请上传流程配置文件！", "" ) );
			return null;
		}
		Deployment deployment = repositoryService.createDeployment().name( getProcessKey() ).key( getProcessKey() ).addBytes( uploadFile.getFileName(), uploadFile.getContents() ).deploy();
		
		logger.info( "Deployed process ID: " + deployment.getId() + " KEY " + deployment.getKey() );
		
		return "ok";
	}
	
	public String undeploy( String id ) {
		List<ProcessInstance> list = runtimeService.createProcessInstanceQuery().deploymentId( id ).list();
		for ( ProcessInstance processInstance : list ) {
			runtimeService.deleteProcessInstance( processInstance.getId(), "流程更新" );
		}
		repositoryService.deleteDeployment( id );
		return "ok";
	}

	public List<ProcessDefinition> getResultList() {
		if ( this.resultList == null ) {
			init();
		}
		return resultList;
	}

	private void init() {
		ProcessDefinitionQuery query = repositoryService.createProcessDefinitionQuery();
		this.setResultList( query.list() );
	}

	public void setResultList( List<ProcessDefinition> resultList ) {
		this.resultList = resultList;
	}

	public String getProcessKey() {
		return processKey;
	}

	public void setProcessKey( String processKey ) {
		this.processKey = processKey;
	}

	public UploadedFile getUploadFile() {
		return uploadFile;
	}

	public void setUploadFile( UploadedFile uploadFile ) {
		this.uploadFile = uploadFile;
	}
	
}
